'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import MobileLayout from '../../components/layout/MobileLayout';
import { useSocket, User, Group, FriendRequest } from '../../context/SocketContext';
import styles from './page.module.css';

export default function MessagePage() {
  const router = useRouter();
  const {
    currentUser,
    isConnected,
    login,
    friends,
    groups,
    friendRequests
  } = useSocket();
  
  const [activeTab, setActiveTab] = useState('chats'); // chats, friends, requests
  const [userId, setUserId] = useState(''); // 用于登录输入
  
  // 自动登录或显示登录界面
  useEffect(() => {
    // 如果已经有用户ID，自动登录
    const savedUserId = localStorage.getItem('userId');
    if (savedUserId) {
      login(savedUserId);
    }
  }, [login]);
  
  // 处理登录
  const handleLogin = () => {
    if (userId.trim()) {
      // 检查是否是有效的用户ID（user1, user2, user3）
      if (['user1', 'user2', 'user3'].includes(userId)) {
        login(userId);
        localStorage.setItem('userId', userId);
      } else {
        alert('无效的用户ID，请使用 user1, user2 或 user3');
      }
    }
  };
  
  // 处理打开聊天
  const handleOpenChat = (id: string, type: 'private' | 'group', name: string, avatar: string) => {
    router.push(`/message/chat?id=${id}&type=${type}&name=${name}&avatar=${encodeURIComponent(avatar)}`);
  };
  
  // 处理查看好友信息
  const handleViewFriend = (id: string) => {
    router.push(`/message/friend?id=${id}&mode=view`);
  };
  
  // 处理添加好友
  const handleAddFriend = () => {
    // 这里简化处理，实际应该有搜索功能
    const friendId = prompt('请输入好友ID');
    if (friendId) {
      router.push(`/message/friend?id=${friendId}&mode=add`);
    }
  };
  
  // 处理查看好友请求
  const handleViewRequest = (request: FriendRequest) => {
    router.push(`/message/friend?id=${request.id}&mode=verify`);
  };
  
  // 处理创建群组
  const handleCreateGroup = () => {
    router.push('/message/group?mode=create');
  };
  
  // 处理查看群组信息
  const handleViewGroup = (id: string) => {
    router.push(`/message/group?id=${id}&mode=view`);
  };
  
  // 如果未登录，显示登录界面
  if (!currentUser) {
    return (
      <MobileLayout>
        <div className={styles.loginContainer}>
          <div className={styles.loginForm}>
            <h2 className={styles.loginTitle}>登录聊天</h2>
            <div className={styles.formGroup}>
              <label className={styles.formLabel}>用户ID</label>
              <input 
                type="text" 
                className={styles.formInput}
                placeholder="请输入用户ID"
                value={userId}
                onChange={(e) => setUserId(e.target.value)}
              />
              <div className={styles.formHint}>
                可用ID: user1 (小爱), user2 (妮妮), user3 (风间)
              </div>
            </div>
            <button 
              className={styles.loginButton}
              onClick={handleLogin}
              disabled={!userId.trim()}
            >
              登录
            </button>
          </div>
        </div>
      </MobileLayout>
    );
  }
  
  return (
    <MobileLayout>
      <div className={styles.messagePage}>
        {/* 头部 */}
        <div className={styles.header}>
          <div className={styles.headerTitle}>消息</div>
          <div className={styles.headerActions}>
            {activeTab === 'friends' && (
              <div className={styles.addButton} onClick={handleAddFriend}>
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M19 13H13V19H11V13H5V11H11V5H13V11H19V13Z" fill="#333"/>
                </svg>
              </div>
            )}
            {activeTab === 'chats' && (
              <div className={styles.addButton} onClick={handleCreateGroup}>
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M19 13H13V19H11V13H5V11H11V5H13V11H19V13Z" fill="#333"/>
                </svg>
              </div>
            )}
          </div>
        </div>
        
        {/* 标签页 */}
        <div className={styles.tabs}>
          <div 
            className={`${styles.tab} ${activeTab === 'chats' ? styles.activeTab : ''}`}
            onClick={() => setActiveTab('chats')}
          >
            聊天
          </div>
          <div 
            className={`${styles.tab} ${activeTab === 'friends' ? styles.activeTab : ''}`}
            onClick={() => setActiveTab('friends')}
          >
            好友
          </div>
          <div 
            className={`${styles.tab} ${activeTab === 'requests' ? styles.activeTab : ''}`}
            onClick={() => setActiveTab('requests')}
          >
            验证
            {friendRequests.length > 0 && (
              <span className={styles.badge}>{friendRequests.length}</span>
            )}
          </div>
        </div>
        
        {/* 聊天列表 */}
        {activeTab === 'chats' && (
          <div className={styles.chatsList}>
            {/* 旅游助手 */}
            <div 
              className={`${styles.chatItem} ${styles.travelAssistantItem}`}
              onClick={() => router.push('/message/travel-assistant')}
            >
              <div className={styles.chatAvatar}>
                <Image 
                  src="/travel-assistant-avatar.svg" 
                  alt="旅游助手" 
                  width={50} 
                  height={50} 
                  className={styles.avatar}
                  onError={(e) => {
                    // 如果图片加载失败，使用默认图片
                    const target = e.target as HTMLImageElement;
                    target.src = 'https://placehold.co/50x50?text=TA';
                  }}
                />
              </div>
              <div className={styles.chatInfo}>
                <div className={styles.chatName}>旅游助手</div>
                <div className={styles.chatLastMessage}>
                  智能旅游规划与推荐
                </div>
              </div>
              <div className={styles.chatMeta}>
                <div className={styles.aiTag}>AI</div>
              </div>
            </div>
            
            {/* 好友聊天 */}
            {friends.map((friend: User) => (
              <div 
                key={`friend-${friend.id}`} 
                className={styles.chatItem}
                onClick={() => handleOpenChat(friend.id, 'private', friend.username, friend.avatar)}
              >
                <div className={styles.chatAvatar}>
                  <Image 
                    src={friend.avatar} 
                    alt={friend.username} 
                    width={50} 
                    height={50} 
                    className={styles.avatar}
                  />
                  {friend.online && <div className={styles.onlineIndicator} />}
                </div>
                <div className={styles.chatInfo}>
                  <div className={styles.chatName}>{friend.username}</div>
                  <div className={styles.chatLastMessage}>
                    {friend.lastMessage || '暂无消息'}
                  </div>
                </div>
                <div className={styles.chatMeta}>
                  <div className={styles.chatTime}>
                    {friend.lastMessageTime ? new Date(friend.lastMessageTime).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'}) : ''}
                  </div>
                </div>
              </div>
            ))}
            
            {/* 群组聊天 */}
            {groups.map((group: Group) => (
              <div 
                key={`group-${group.id}`} 
                className={styles.chatItem}
                onClick={() => handleOpenChat(group.id, 'group', group.name, group.avatar)}
              >
                <div className={styles.chatAvatar}>
                  <Image 
                    src={group.avatar} 
                    alt={group.name} 
                    width={50} 
                    height={50} 
                    className={styles.avatar}
                  />
                </div>
                <div className={styles.chatInfo}>
                  <div className={styles.chatName}>{group.name}</div>
                  <div className={styles.chatLastMessage}>
                    {group.lastMessage || '暂无消息'}
                  </div>
                </div>
                <div className={styles.chatMeta}>
                  <div className={styles.chatTime}>
                    {group.lastMessageTime ? new Date(group.lastMessageTime).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'}) : ''}
                  </div>
                </div>
              </div>
            ))}
            
            {friends.length === 0 && groups.length === 0 && (
              <div className={styles.emptyState}>
                <div className={styles.emptyIcon}>
                  <svg width="64" height="64" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M20 2H4C2.9 2 2 2.9 2 4V22L6 18H20C21.1 18 22 17.1 22 16V4C22 2.9 21.1 2 20 2ZM20 16H5.17L4 17.17V4H20V16Z" fill="#999"/>
                    <path d="M12 15H14V17H12V15ZM12 7H14V13H12V7Z" fill="#999"/>
                  </svg>
                </div>
                <div className={styles.emptyText}>暂无聊天</div>
                <div className={styles.emptySubtext}>添加好友或创建群组开始聊天</div>
              </div>
            )}
          </div>
        )}
        
        {/* 好友列表 */}
        {activeTab === 'friends' && (
          <div className={styles.friendsList}>
            {friends.map((friend: User) => (
              <div 
                key={friend.id} 
                className={styles.friendItem}
                onClick={() => handleViewFriend(friend.id)}
              >
                <div className={styles.friendAvatar}>
                  <Image 
                    src={friend.avatar} 
                    alt={friend.username} 
                    width={50} 
                    height={50} 
                    className={styles.avatar}
                  />
                  {friend.online && <div className={styles.onlineIndicator} />}
                </div>
                <div className={styles.friendInfo}>
                  <div className={styles.friendName}>{friend.username}</div>
                  <div className={styles.friendStatus}>
                    {friend.online ? '在线' : '离线'}
                  </div>
                </div>
                <div className={styles.friendAction}>
                  <div className={styles.chatButton} onClick={(e) => {
                    e.stopPropagation();
                    handleOpenChat(friend.id, 'private', friend.username, friend.avatar);
                  }}>
                    聊天
                  </div>
                </div>
              </div>
            ))}
            
            {friends.length === 0 && (
              <div className={styles.emptyState}>
                <div className={styles.emptyIcon}>
                  <svg width="64" height="64" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M16 11C17.66 11 18.99 9.66 18.99 8C18.99 6.34 17.66 5 16 5C14.34 5 13 6.34 13 8C13 9.66 14.34 11 16 11ZM8 11C9.66 11 10.99 9.66 10.99 8C10.99 6.34 9.66 5 8 5C6.34 5 5 6.34 5 8C5 9.66 6.34 11 8 11ZM8 13C5.67 13 1 14.17 1 16.5V19H15V16.5C15 14.17 10.33 13 8 13ZM16 13C15.71 13 15.38 13.02 15.03 13.05C16.19 13.89 17 15.02 17 16.5V19H23V16.5C23 14.17 18.33 13 16 13Z" fill="#999"/>
                  </svg>
                </div>
                <div className={styles.emptyText}>暂无好友</div>
                <div className={styles.emptySubtext}>点击右上角添加好友</div>
              </div>
            )}
          </div>
        )}
        
        {/* 好友请求列表 */}
        {activeTab === 'requests' && (
          <div className={styles.requestsList}>
            {friendRequests.map((request: FriendRequest) => (
              <div 
                key={request.id} 
                className={styles.requestItem}
                onClick={() => handleViewRequest(request)}
              >
                <div className={styles.requestAvatar}>
                  <Image 
                    src={request.senderAvatar || '/avatars/avatar1.svg'} 
                    alt={request.senderName || '用户'} 
                    width={50} 
                    height={50} 
                    className={styles.avatar}
                  />
                </div>
                <div className={styles.requestInfo}>
                  <div className={styles.requestName}>
                    {request.senderName || '用户'}
                  </div>
                  <div className={styles.requestMessage}>
                    {request.message}
                  </div>
                </div>
                <div className={styles.requestStatus}>
                  {request.status === 'pending' ? '待处理' : 
                   request.status === 'accepted' ? '已接受' : '已拒绝'}
                </div>
              </div>
            ))}
            
            {friendRequests.length === 0 && (
              <div className={styles.emptyState}>
                <div className={styles.emptyIcon}>
                  <svg width="64" height="64" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M12 2C6.48 2 2 6.48 2 12C2 17.52 6.48 22 12 22C17.52 22 22 17.52 22 12C22 6.48 17.52 2 12 2ZM12 20C7.59 20 4 16.41 4 12C4 7.59 7.59 4 12 4C16.41 4 20 7.59 20 12C20 16.41 16.41 20 12 20ZM16.59 7.58L10 14.17L7.41 11.59L6 13L10 17L18 9L16.59 7.58Z" fill="#999"/>
                  </svg>
                </div>
                <div className={styles.emptyText}>暂无好友请求</div>
              </div>
            )}
          </div>
        )}
      </div>
    </MobileLayout>
  );
}